package com.fpost.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.fpost.constants.ActionConstants;
import com.fpost.domain.Article;
import com.fpost.domain.ArticleVersion;
import com.fpost.form.CreateArticleForm;
import com.fpost.form.dto.UserDTO;
import com.fpost.manager.ArticleManager;
import com.fpost.manager.DictionaryManager;
import com.fpost.security.ActionSecurityUtils;
import com.fpost.util.ActionUtils;
import com.fpost.util.CommonUtils;
import com.fpost.util.DateUtil;
import com.fpost.util.FpostCache;

public class UpdateArticleAction extends Action {
	
	private static Logger log = Logger.getLogger(UpdateArticleAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
				
		String forward = ActionConstants.SUCCESS;

		try {
			ArticleManager articleManager = new ArticleManager();
			long articleId = Long.parseLong(request.getParameter("articleId"));

			UserDTO userDTO = ActionSecurityUtils.getUserDTO_fromSession(request);
			if (userDTO == null) {
				forward = ActionConstants.LOGIN;
			} else if (!ActionSecurityUtils.isUpdateAllowed(Long.parseLong(userDTO.getUserId()), articleId)) {
				ActionUtils.setErrorMessage(request, "error.article.update.not.allowed");
				forward = ActionConstants.FAILURE;
			} else {	
				CreateArticleForm createArticleForm = (CreateArticleForm) form;
				createArticleForm.setArticleTypeDTOList(FpostCache.getInstance().getArticleTypeDTOList());

				Article article = articleManager.getArticleById(articleId);
				if ("GET".equals(request.getMethod())) {
					// on first load show the article content
					createArticleForm.setArticleId(String.valueOf(article.getArticleId()));

					createArticleForm.setAuthorFirstName(article.getUser().getFirstName());
					createArticleForm.setAuthorLastName(article.getUser().getLastName());
					createArticleForm.setAuthorUsername(article.getUser().getUsername());

					ArticleVersion latestVersion = article.getVersions().get(0);

					createArticleForm.setArticleTypeId(String.valueOf(latestVersion.getArticleTypeId()));
					createArticleForm.setTitle(latestVersion.getTitle());
					createArticleForm.setSummary(CommonUtils.restoreLineSeparator(latestVersion.getSummary()));
					createArticleForm.setBody(CommonUtils.restoreLineSeparator(latestVersion.getBody()));
					createArticleForm.setKeywords(latestVersion.getKeywords());

					forward = ActionConstants.RELOAD;
					
				} else if ("POST".equals(request.getMethod())) {
					// save data to db
					//article.setUser(article.getUser());

					ArticleVersion version = new ArticleVersion();
					version.setArticleTypeId(Long.parseLong(createArticleForm.getArticleTypeId()));
					version.setTitle(createArticleForm.getTitle());
					version.setCreatedOn(DateUtil.getGMTCalendar().getTime());
					version.setCreatedIp(request.getRemoteAddr());
					version.setSummary(CommonUtils.replaceLineSeparator(createArticleForm.getSummary()));
					version.setBody(CommonUtils.replaceLineSeparator(createArticleForm.getBody()));
					version.setKeywords(createArticleForm.getKeywords());
					//version.setLatestVersion(true);

					article.getVersions().add(version);
					
					articleManager.saveOrUpdate(article);
					
					//add new words to dictionary
					new DictionaryManager().addNewWords(article.getArticleId());
					ActionUtils.setErrorMessage(request, "info.article.successfully.updated");
					forward = ActionConstants.SUCCESS;					
				}
			}
		} catch (NumberFormatException e) {
			log.error(e.getMessage(), e);
			ActionUtils.setErrorMessage(request, "error.article.update.failed");
			forward = ActionConstants.FAILURE;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.getMessage(), e);
			forward = ActionConstants.SYSTEM_FAILURE;
		}

		return mapping.findForward(forward);

	}

}
